package com.ybkj.daijia.api.jpush;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Message.Builder;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.google.gson.Gson;
import com.ybkj.daijia.PushDataV4;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.server.model.Driver;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JiGuangEmployV4 {

    private static final Logger logger = LoggerFactory.getLogger(JiGuangEmployV4.class);

//	private static final String appKey ="c36583e061c75015dec15db6";  
//    private static final String masterSecret = "cb0921fcb84153cd4d181f54";  

    public static void push(Driver driver, PushDataV4 pushDataV4, Setting setting) {

        String appKey = setting.getJiguangEmployAppKey();
        String masterSecret = setting.getJiguangEmployMasterSecret();
        String appKeyGeneral = setting.getJiguangEmployAppKeyGeneral();
        String masterSecretGeneral = setting.getJiguangEmployMasterSecretGeneral();

        if (StringUtils.isNotBlank(appKey) && StringUtils.isNotBlank(masterSecret)) {
            try {
                JPushClient jpushClient = new JPushClient(masterSecret, appKey);
                // For push, all you need do is to build PushPayload object.
                PushPayload payload = buildPush(driver.getRegistrationId(), pushDataV4);
                PushResult result = jpushClient.sendPush(payload);
                logger.debug("Got result - " + result);

            } catch (APIConnectionException e) {
                // Connection error, should retry later
                logger.debug("Connection error, should retry later", e);

            } catch (APIRequestException e) {
                // Should review the error, and fix the request
                logger.debug("Should review the error, and fix the request", e);
                logger.debug("HTTP Status: " + e.getStatus());
                logger.debug("Error Code: " + e.getErrorCode());
                logger.debug("Error Message: " + e.getErrorMessage());
            }
        }
        if (StringUtils.isNotBlank(appKeyGeneral) && StringUtils.isNotBlank(masterSecretGeneral)) {
            try {
                JPushClient jpushClient = new JPushClient(masterSecretGeneral, appKey);
                // For push, all you need do is to build PushPayload object.
                PushPayload payload = buildPush(driver.getRegistrationId(), pushDataV4);
                PushResult result = jpushClient.sendPush(payload);
                logger.debug("Got result - " + result);

            } catch (APIConnectionException e) {
                // Connection error, should retry later
                logger.debug("Connection error, should retry later", e);

            } catch (APIRequestException e) {
                // Should review the error, and fix the request
                logger.debug("Should review the error, and fix the request", e);
                logger.debug("HTTP Status: " + e.getStatus());
                logger.debug("Error Code: " + e.getErrorCode());
                logger.debug("Error Message: " + e.getErrorMessage());
            }
        }

    }

    public static void notice(Driver driver, String title, String text, Setting setting) {

        String appKey = setting.getJiguangEmployAppKey();
        String masterSecret = setting.getJiguangEmployMasterSecret();

        if (StringUtils.isNotBlank(appKey) && StringUtils.isNotBlank(masterSecret)) {
            JPushClient jpushClient = new JPushClient(masterSecret, appKey);

            // For push, all you need do is to build PushPayload object.
            PushPayload payload = buildNotice(driver.getRegistrationId(), title, text);

            try {
                PushResult result = jpushClient.sendPush(payload);
                logger.debug("Got result - " + result);

            } catch (APIConnectionException e) {
                // Connection error, should retry later
                logger.debug("Connection error, should retry later", e);

            } catch (APIRequestException e) {
                // Should review the error, and fix the request
                logger.debug("Should review the error, and fix the request", e);
                logger.debug("HTTP Status: " + e.getStatus());
                logger.debug("Error Code: " + e.getErrorCode());
                logger.debug("Error Message: " + e.getErrorMessage());
            }
        }

    }


    public static PushPayload buildPush(String registrationId, PushDataV4 pushDataV4) {

        Gson gson = new Gson();

        Map<String, String> extra = pushDataV4.getExtra();

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("code", pushDataV4.getCode());
        data.put("type", pushDataV4.getType());
        data.put("data", pushDataV4.getData());
        data.put("time", pushDataV4.getTime());
        data.put("sound", pushDataV4.getSound());
        if (pushDataV4.getCode().equals("0X10")) {
            data.put("extra", extra);
        }

        Builder builder = Message.newBuilder();
        builder.setMsgContent(gson.toJson(data));

        String sound = "default";
        if (StringUtils.isNotBlank(pushDataV4.getSound())) {
            sound = pushDataV4.getSound();
        }

        String content = extra.get("content");
        if (StringUtils.isNotBlank(content) && content.length() > 40) {
            content = content.substring(0, 40) + "...";
        }

        return PushPayload.newBuilder()
            .setPlatform(Platform.android_ios())
            .setAudience(Audience.registrationId(registrationId))
            .setNotification(Notification.newBuilder()
                .addPlatformNotification(IosNotification.newBuilder()
                    .setSound(sound + ".mp3")
                    .setAlert(content)
                    .addExtra("extra", gson.toJson(data))
                    .setBadge(0)
                    .build())
                .build())
            .setMessage(builder
                .build())
            .setOptions(Options.newBuilder()
                .setTimeToLive(0)//离线消息保留时长 默认 86400 （1 天）
                .setApnsProduction(true)//TRUE生产 false开发
                .build()
            )
            .build();
    }

    public static PushPayload buildNotice(String registrationId, String title, String text) {

        return PushPayload.newBuilder()
            .setPlatform(Platform.android_ios())
            .setAudience(Audience.newBuilder()
                .addAudienceTarget(AudienceTarget.registrationId(registrationId))
                .build())
            .setNotification(Notification.newBuilder()
                .addPlatformNotification(IosNotification.newBuilder()
                    .setAlert(text)
                    .build())
                .addPlatformNotification(AndroidNotification.newBuilder()
                    .setAlert(text)
                    .setTitle(title)
                    .build())
                .build())
            .setOptions(Options.newBuilder()
                .setTimeToLive(0)//离线消息保留时长 默认 86400 （1 天）
                .setApnsProduction(true)//TRUE生产 false开发
                .build()
            )
            .build();
    }

//	public static void main(String[] args) {
//		PushData pushData=new PushData();
//		pushData.setData(444);
//		pushData.setTitle("标题");
//		pushData.setDescription("内容");
//		pushData.setType("test_type");
//		push("123456",pushData,null);
//	}
}
